package com.powernode.controller;

import com.powernode.common.Constants;
import com.powernode.domain.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("upload")
public class uploadController {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSss");

    private Random random = new Random();

    @Resource
    private UserService userService;

    @RequestMapping("uploadImg.action")
    public Result uploadImg(MultipartFile mf, HttpSession session){
        String oldName = mf.getOriginalFilename();
        String newName = createNew(oldName);
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER_KEY);
            User user2 = userService.selectByPrimaryKey(user.getId());
            mf.transferTo(new File(Constants.ROOTPATH,newName));
            user2.setImg(newName);
            userService.updateByPrimaryKeySelective(user2);
            return new Result(200,"上传成功",0L,user2.getImg());
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(200,"文件上传失败");
        }
    }

    private String createNew(String oldName) {
        String end =oldName.substring(oldName.lastIndexOf("."));
        return sdf.format(new Date())+(random.nextInt(90000)+10000)+end;
    }
}
